package tchatrmi;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;


/**
 * Tchat en Java RMI
 * @author Toto
 * @version 1.0
 */
public class Client {

	/**
	 * Nom par dfaut de la machine o tourne le registre RMI
	 */
	private static String DEFAULT_HOST = "localhost";

	/**
	 * Port par dfaut du registre RMI distant
	 */
	private static int DEFAULT_REGISTRY_PORT = 1099;


	/**
	 * 
	 * @param args
	 */
	public static void main (String[] args) {		

		ServeurInterface serveurChat = null;
		String server = null;
		int port = -1;
		
		String nomClient;
		String adresseClient = "localhost";
		String url;

		
		if(args.length != 2) {
			System.out.println("Usage: java chatrmi.Client NomServeur PortServeur");
			System.out.println("Utilisation du nom de serveur et du port par dfaut ("+DEFAULT_HOST+":"+DEFAULT_REGISTRY_PORT+")");
			server = DEFAULT_HOST;
			port = DEFAULT_REGISTRY_PORT;
		}
		else {
			try {
				server = args[0];
				port = Integer.parseInt(args[1]);
			}
			catch(NumberFormatException nfe) {
				nfe.printStackTrace();
				System.exit(1);
			}
		}

		
		IHM ihm = new IHM();

		
		System.out.print("Votre nom : ");
		nomClient = LectureChaine.lireChaine();

		try {
			adresseClient = InetAddress.getLocalHost().getHostAddress();
		} 
		catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		url = "rmi://" + adresseClient + ":" + port + "/" + nomClient;

		
		System.setSecurityManager(new RMISecurityManager()); 
		
		
		ClientImpl clientChat;
		
		try {
			clientChat = new ClientImpl(nomClient, ihm);
			Naming.rebind("rmi://localhost:"+port+"/"+nomClient, clientChat);
		} 
		catch (RemoteException e1) {
			e1.printStackTrace();
		} 
		catch (MalformedURLException e) {
			e.printStackTrace();
		}

		
		
		ihm.go();
		
		
		
				
		try {
			serveurChat = (ServeurInterface) Naming.lookup("rmi://"+server+":"+port+"/Serveur");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (NotBoundException e) {
			e.printStackTrace();
		}

				
		try {
			serveurChat.enregistrer(url);
		} 
		catch (RemoteException e) {
			e.printStackTrace();
		}
		
				
		
		Thread threadEnvoyer = new Thread (new ClientEnvoyerMessage(nomClient, ihm, serveurChat));
		threadEnvoyer.start();   
		
	}


}


